package com.zb.callback.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zb.callback.entity.LKaiBOrderVo;
import com.zb.callback.entity.LKaiOrderVo;
import com.zb.callback.service.LKaiService;
import com.zb.constant.WorkConstant;
import com.zb.entity.*;
import com.zb.http.HttpClientUtil;
import com.zb.service.*;
import com.zb.service.impl.WorkServiceLog;
import com.zb.util.DownLoadNetworkFileUtil;
import com.zb.utils.RandomUtil;
import com.zb.utils.ZbDateUtil;
import com.zb.utils.ZbOrderNoUtil;
import com.zb.view.ViewGoods;
import com.zb.vo.WorkFeeLogVo;
import com.zb.vo.WorkLogVo;
import com.zb.yaml.DomainPath;
import com.zb.yaml.FilePath;
import com.zb.yaml.HoubanYunOrder;
import com.zb.yaml.HoubanYunSecret;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * @Author WEN
 * @Date 2024/8/21 0021
 **/
@Log4j2
@Service
public class LkaiServiceImpl implements LKaiService {
    @Resource
    private ZjWorkModuleService workModuleService;
    @Resource
    private ZjUserService userService;
    @Resource
    private ZjWorkOrderService workOrderService;
    @Resource
    private ZjWorkDetailService workDetailService;
    @Resource
    private ZjWorkUserService workUserService;
    @Resource
    private ZjWorkGoodsService workGoodsService;
    @Resource
    private ZjWorkGoodsCodeService workGoodsCodeService;
    @Resource
    private ViewGoodsService viewGoodsService;
    @Resource
    private ZjWorkHoubanYunRelationService workHoubanYunRelationService;
    @Resource
    private ZjFactoryService factoryService;
    @Resource
    private ZjWorkLevelService workLevelService;
    @Resource
    private ZjWorkFeeService workFeeService;
    @Resource
    private ZjWorkFeeDetailService workFeeDetailService;
    @Resource
    private ZjWorkFieldValService workFieldValService;
    @Resource
    private ZjWorkFieldValOptionService workFieldValOptionService;
    @Resource
    private ZjWorkImageService workImageService;
    @Resource
    private ZjCustomerService customerService;
    @Resource
    private ZjWorkDispatchNetworkService workDispatchNetworkService;
    @Resource
    private ZjWorkDispatchEngineerService workDispatchEngineerService;
    @Resource
    private ZjWorkFinishOrderService workFinishOrderService;
    @Resource
    private ZjWorkHoubanYunNetworkService workHoubanYunNetworkService;
    @Resource
    private ZjWorkThirdPushDataService workThirdPushDataService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String EVENT_TYPE = "item.update"; // 修改的事件类型
    private static final String[] LKAI_NETWORK_ID = {"2300013506009685", "2300013506008283", "2300013505991588", "2300013462542235", "2300013896959979", "2300013919779174"}; // 叮咚工单的ID

    // 保存工单
    @Override
    @Transactional
    public synchronized void saveCOrder(String data) {
        JSONObject obj = JSON.parseObject(data, JSONObject.class);
        if (null == obj) {
            return;
        }
        JSONObject headerObj = JSON.parseObject(obj.getString("header"), JSONObject.class);
        // 过滤掉事件类型不是 item.update 的数据
        if (null == headerObj || !Objects.equals(EVENT_TYPE, headerObj.getString("event_type"))) {
            return;
        }
        JSONObject dataObj = JSON.parseObject(obj.getString("data"), JSONObject.class);
        if (null == dataObj) {
            return;
        }
        JSONObject itemObj = JSON.parseObject(dataObj.getString("item"), JSONObject.class);
        if (null == itemObj) {
            return;
        }
        // 过滤掉非叮咚的工单数据
        JSONObject fieldsObj = JSON.parseObject(itemObj.getString("fields"), JSONObject.class);
        // 负责服务商，过滤非叮咚的工单
        List<JSONObject> ddNetworkObjs = JSON.parseArray(fieldsObj.getString("2200000469555705"), JSONObject.class);
        if (CollectionUtil.isEmpty(ddNetworkObjs)) {
            log.info("伙伴云推送的数据(没有服务商字段或服务商字段为空，不做处理)，item_id：{}，工单号：{}， 时间：{}",
                    itemObj.getString("item_id"),
                    fieldsObj.getString("2200000469555672"),
                    DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            return;
        }
        // 记录推送的数据
        workThirdPushDataService.save(HoubanYunOrder.getCustAccId(), 1, fieldsObj.getString("2200000469555672"), data);

        JSONObject ddNetworkObj = ddNetworkObjs.get(0);
        if (!workHoubanYunNetworkService.existByHoubanYunNetworkItemId(HoubanYunOrder.getCustAccId(), ddNetworkObj.getString("item_id"))) {
            return;
        }
        Date createdOn = itemObj.getDate("created_on");
        Date appointDate = ZbDateUtil.getAppointDate("2024-08-30", ZbDateUtil.DATE_FORMAT);
        if (null == appointDate) {
            return;
        }
        if (createdOn.before(appointDate)) {
            return;
        }
        LKaiOrderVo kaiOrderVo = new LKaiOrderVo();
        kaiOrderVo.setItemId(itemObj.getString("item_id"));
        JSONObject createdBy = JSON.parseObject(itemObj.getString("created_by"), JSONObject.class);
        kaiOrderVo.setCreatedByName(null != createdBy? createdBy.getString("name") : "");
        kaiOrderVo.setCreatedTime(createdOn);

        JSONObject updatedBy = JSON.parseObject(itemObj.getString("updated_by"), JSONObject.class);
        kaiOrderVo.setUpdateByName(null != updatedBy? updatedBy.getString("name") : "");
        kaiOrderVo.setUpdateTime(itemObj.getDate("updated_on"));
        kaiOrderVo.setTitle(itemObj.getString("title"));
        kaiOrderVo.setOrderNo(fieldsObj.getString("2200000469555672"));
        kaiOrderVo.setModule(getTitle(fieldsObj,  "2200000469555676"));
        kaiOrderVo.setLevel(getTitle(fieldsObj, "2200000469555695"));
        kaiOrderVo.setSource(getTitle(fieldsObj,  "2200000469555674"));
        kaiOrderVo.setUserType(getTitle(fieldsObj,  "2200000469555677"));
        kaiOrderVo.setUsername(fieldsObj.getString("2200000469555679"));
        kaiOrderVo.setUserPhone(fieldsObj.getString("2200000469555680"));
        kaiOrderVo.setProvince(getTitle(fieldsObj,  "2200000469555681"));
        kaiOrderVo.setCity(getTitle(fieldsObj,  "2200000471123863"));
        kaiOrderVo.setArea(getTitle(fieldsObj,  "2200000471123864"));
        kaiOrderVo.setAddress(fieldsObj.getString("2200000469555693"));
        kaiOrderVo.setGoodsType(getTitle(fieldsObj,  "2200000469555684"));
        kaiOrderVo.setGoodsModel(fieldsObj.getString("2200000469555685"));
        if (Objects.equals("安装", kaiOrderVo.getModule())) {
            kaiOrderVo.setSnCode(getTitle(fieldsObj,  "2200000471551057"));
        } else {
            kaiOrderVo.setSnCode(getTitle(fieldsObj,  "2200000478776456"));
        }
        kaiOrderVo.setContent(fieldsObj.getString("2200000469555686"));
        kaiOrderVo.setQty(fieldsObj.getInteger("2200000469555688"));
        kaiOrderVo.setHandlerTime(fieldsObj.getDate("2200000469555703"));
        kaiOrderVo.setTotalFee(fieldsObj.getBigDecimal("2200000469555716"));
        kaiOrderVo.setFee1(fieldsObj.getBigDecimal("2200000469555700")); // 基础费
        kaiOrderVo.setFee2(fieldsObj.getBigDecimal("2200000469555712")); // 加急费
        kaiOrderVo.setFee3(fieldsObj.getBigDecimal("2200000469555713")); // 开锁费
        kaiOrderVo.setFee4(fieldsObj.getBigDecimal("2200000469555715")); // 远程费
        kaiOrderVo.setFee5(fieldsObj.getBigDecimal("2200000469559104")); // 使用师傅配件费
        // 安装字段
        kaiOrderVo.setCInstallOrderField1(fieldsObj.getString("2200000471328682"));
        kaiOrderVo.setCInstallOrderField2(fieldsObj.getString("2200000471328683"));
        kaiOrderVo.setCInstallOrderField3(fieldsObj.getString("2200000471328684"));
        kaiOrderVo.setCInstallOrderField4(fieldsObj.getString("2200000469555691"));
        // 上传完整产品图片
        List<String> imgFields1  =new ArrayList<>();
        getImageId(fieldsObj, "2200000497522714", imgFields1);
        kaiOrderVo.setCInstallOrderField7(getBatchFiles(imgFields1));
        // 门体视频
        List<String> imgFields2  =new ArrayList<>();
        getImageId(fieldsObj, "2200000497522715", imgFields2);
        kaiOrderVo.setCInstallOrderField8(getBatchFiles(imgFields2));

        kaiOrderVo.setCInstallOrderField9(getTitle(fieldsObj, "2200000497522716")); // 门体属性
        kaiOrderVo.setCInstallOrderField10(getTitle(fieldsObj, "2200000497522717")); // 有无天地钩
        kaiOrderVo.setCInstallOrderField11(fieldsObj.getString("2200000469555709")); // 期望上门时间
        // 维修
        kaiOrderVo.setCancelOrderId(getIdVal(fieldsObj, "2200000469555696"));
        kaiOrderVo.setCUpdateOrderField1(getTitle(fieldsObj, "2200000469555696")); // 服务受理状态
        kaiOrderVo.setCUpdateOrderField2(getTitle(fieldsObj, "2200000469555698"));
        kaiOrderVo.setCUpdateOrderField3(getTitle(fieldsObj, "2200000469555697"));
        kaiOrderVo.setTeleCustomProIdenCode(getTitle(fieldsObj, "2200000471551057")); // 电信客户产品识别码
        //客户类型
        kaiOrderVo.setCustomType(getTitle(fieldsObj, "2200000469555677"));
        //产品分类
        kaiOrderVo.setProductType(getTitle(fieldsObj, "2200000469555684"));
        //产品品牌
        kaiOrderVo.setProductBrand(getTitle(fieldsObj, "2200000489295091"));
        //产品名称
        kaiOrderVo.setProductName(getTitle(fieldsObj, "2200000489295140"));
        //
        List<String> fileIds = new ArrayList<>();
        getImageId(fieldsObj, "2200000470499139", fileIds); // 封面
        getImageId(fieldsObj, "2200000471328685", fileIds); // 门体侧面照片
        getImageId(fieldsObj, "2200000471536074", fileIds); // 门体正面照片
        kaiOrderVo.setSourceImage(getBatchFiles(fileIds));
        // 查伙伴云工单
        ZjWorkHoubanYunRelation houbanYunRelation = workHoubanYunRelationService.getByItemId(kaiOrderVo.getItemId());
        Long workId = null;
        // 是否取消工单
        Boolean cancelOrder = cancelOrder(kaiOrderVo);
        // 修改
        if (null != houbanYunRelation) {
            ZjWorkOrder order = new ZjWorkOrder();
            order.setId(houbanYunRelation.getId());
            order.setCode(kaiOrderVo.getOrderNo());
            order.setCustomType(kaiOrderVo.getCustomType());
            order.setProductType(kaiOrderVo.getProductType());
            order.setProductBrand(kaiOrderVo.getProductBrand());
            order.setProductName(kaiOrderVo.getProductName());
            order.setCancelReason(1);
            order.setTeleCustomProIdenCode(kaiOrderVo.getTeleCustomProIdenCode());
            if (null != kaiOrderVo.getFee1()) {
//                order.setModulePrice(kaiOrderVo.getFee1());
            }
            if (cancelOrder) {
                order.setStatus(WorkConstant.WORK_STATUS_5);
            }
            order.setWorkLevelId(getOrderLevel(kaiOrderVo.getLevel()));
            order.setUpdateEmp(kaiOrderVo.getUpdateByName());
            order.setGmtUpdate(kaiOrderVo.getUpdateTime());
            workOrderService.updateById(order);
            WorkServiceLog.saveLKaiHoubanyunOrder(new WorkLogVo(HoubanYunOrder.getCustAccId(), "乐开伙伴云", order.getId(), cancelOrder? "乐开伙伴云取消工单" : "乐开伙伴云更新工单"));
            workId = order.getId();

            // 工单客户
            ZjWorkUser workUser = new ZjWorkUser();
            workUser.setId(order.getId());
            workUser.setName(kaiOrderVo.getUsername());
            workUser.setPhone(kaiOrderVo.getUserPhone());
            workUser.setOtherPhone("");
            workUser.setProvince(kaiOrderVo.getProvince());
            workUser.setCity(kaiOrderVo.getCity());
            workUser.setArea(null == kaiOrderVo.getArea()? "" : kaiOrderVo.getArea());
            workUser.setTown("");
            if (null != kaiOrderVo.getAddress()) {
                workUser.setAddress(kaiOrderVo.getAddress());
            }
            workUserService.updateById(workUser);
            ZjWorkDetail workDetail = workDetailService.getById(workId);
            // 工单费用
            Integer workFeeCount = workFee(workId, kaiOrderVo);

            ZjWorkDetail detail = new ZjWorkDetail();
            detail.setId(order.getId());
            detail.setNoReviewApplyWorkFeeNum(0);
            detail.setContent(null == kaiOrderVo.getContent() ? "" : kaiOrderVo.getContent());
            if (cancelOrder) {
                updateDispatchNetworkStatus(order.getId());
                detail.setNoReviewApplyWorkFeeNum(0);
                detail.setEndOrderApply(false);
            }
            workDetailService.updateById(detail);
        } else {
            // 先判断是否重复
            String formattedTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            Boolean success = redisTemplate.opsForValue().setIfAbsent(kaiOrderVo.getOrderNo(), formattedTime, 1, TimeUnit.HOURS);
            if (Boolean.FALSE.equals(success)) {
                // 如果返回 false，说明 key 已经存在，避免重复处理
                log.error("该订单号已存在：" + kaiOrderVo.getOrderNo());
                return;
            }
            LambdaQueryWrapper<ZjWorkOrder> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ZjWorkOrder::getCode, kaiOrderVo.getOrderNo());
            int count = workOrderService.count(wrapper);
            if (count > 0) {
                return;
            }
            // 查询工单模块
            // 安装
            ZjWorkModule module = null;
            ViewGoods viewGoods = null;
            ZjFactory factory = factoryService.getById(HoubanYunOrder.getFactoryId());
            if (Objects.equals("安装", kaiOrderVo.getModule())) {
                module = workModuleService.getById(HoubanYunOrder.getcInstallModuleId());
                viewGoods = viewGoodsService.getByGoodsTypeAndGoodsIdAndGoodsSpecId(1, HoubanYunOrder.getcInstallGoodsId(), HoubanYunOrder.getcInstallGoodsSpecId());
            } else {
                module = workModuleService.getById(HoubanYunOrder.getcUpdateModuleId());
                viewGoods = viewGoodsService.getByGoodsTypeAndGoodsIdAndGoodsSpecId(1, HoubanYunOrder.getcUpdateGoodsId(), HoubanYunOrder.getcUpdateGoodsSpecId());
            }
            // 工单数据
            ZjWorkOrder order = new ZjWorkOrder();
            order.setId(IdWorker.getId());
            order.setCustAccId(HoubanYunOrder.getCustAccId()); // 固定
            order.setFactoryId(HoubanYunOrder.getFactoryId()); // 固定
            order.setCode(kaiOrderVo.getOrderNo());
            order.setTeleCustomProIdenCode(kaiOrderVo.getTeleCustomProIdenCode());
            order.setStatus(cancelOrder? WorkConstant.WORK_STATUS_5 : WorkConstant.WORK_STATUS_1);
            order.setArchived(false);
            order.setModuleId(module.getId()); // 固定
            order.setAssignEmp(false);
            order.setEmpId(0L);
            order.setAssignEmpTime(null);
            order.setNetworkId(0L);
            order.setNetworkEmpId(0L);
            order.setEndTime(null);
            order.setNewAdvance(0);
            order.setWaitCopeEvent(0);
            order.setOverinsured(module.getOverinsured()); // 根据模块取
            order.setReminderNum(0);
            order.setWarrantyDay(module.getWarrantyDay()); // 根据模块取
            order.setSource(WorkConstant.WORK_SOURCE_9); // 来源
            order.setWorkLevelId(getOrderLevel(kaiOrderVo.getLevel()));
            order.setAllInclusiveFee(false);
            order.setModulePrice(new BigDecimal("0.00"));
            order.setNetworkModulePrice(new BigDecimal("0.00"));
            order.setCollectCustomerPrice(new BigDecimal("0.00"));
            order.setFactorySettlementDeductionPrice(new BigDecimal("0.00"));
            order.setNetworkSettlementDeductionPrice(new BigDecimal("0.00"));
            order.setEndOrder(false);
            order.setSettlementStatus(WorkConstant.WORK_SETTLEMENT_STATUS_0);
            order.setWithdrawFreezeDay(0);
            order.setComment(false);
            order.setChangeOrder(false);
            order.setSuspendStatus(0);
            order.setCreateEmpType(4);
            order.setCreateEmpId(0L);
            order.setCreateEmp(kaiOrderVo.getCreatedByName());
            order.setUpdateEmpId(0L);
            order.setUpdateEmp(kaiOrderVo.getUpdateByName());
            order.setFactoryRemark("");
            order.setCreateFactory(null == factory ? "" : factory.getName());
            order.setGmtCreate(kaiOrderVo.getCreatedTime());
            order.setGmtUpdate(kaiOrderVo.getUpdateTime());
            order.setCustomType(kaiOrderVo.getCustomType());
            order.setProductType(kaiOrderVo.getProductType());
            order.setProductBrand(kaiOrderVo.getProductBrand());
            order.setProductName(kaiOrderVo.getProductName());
            order.setCancelReason(1);
            workOrderService.save(order);
            log.info("乐开C端推送工单order:{}", order);

            WorkServiceLog.saveLKaiHoubanyunOrder(new WorkLogVo(order.getCustAccId(), "乐开伙伴云", order.getId(), "乐开伙伴云创建工单"));
            workId = order.getId();
            // 工单费用
            Integer workFeeCount = workFee(workId, kaiOrderVo);
            // 工单详细数据
            ZjWorkDetail detail = new ZjWorkDetail();
            detail.setId(order.getId());
            detail.setCustAccId(order.getCustAccId());
            detail.setOneTypeId(0L);
            detail.setTwoTypeId(0L);
            detail.setThreeTypeId(0L);
            detail.setOneWayId(0L);
            detail.setTwoWayId(0L);
            detail.setThreeWayId(0L);
            detail.setContent(null == kaiOrderVo.getContent() ? "" : kaiOrderVo.getContent());
            detail.setNoReviewApplyWorkFeeNum(0);
            detail.setNoReviewApplyWorkSpareNum(0);
            detail.setEndOrderApply(false);
            detail.setCancelOrderApply(false);
            detail.setChangeNetworkApply(false);
            detail.setDispatchEmpId(0L);
            detail.setDispatchTime(null);
            detail.setReservation(false);
            detail.setStatementVerifCode(RandomUtil.randomNumber6());
            detail.setCollectCustomerPriceVoucher("");
            workDetailService.save(detail);

            AccounLoginInfo loginInfo = new AccounLoginInfo(0L, "", "", "", false, "");
            loginInfo.setCustAccId(order.getCustAccId());
            UserInfo userInfo = new UserInfo();
            userInfo.setName(kaiOrderVo.getUsername());
            userInfo.setPhone(kaiOrderVo.getUserPhone());
            userInfo.setProvince(kaiOrderVo.getProvince());
            userInfo.setCity(kaiOrderVo.getCity());
            userInfo.setArea(null == kaiOrderVo.getArea()? "" : kaiOrderVo.getArea());
            userInfo.setTown("");
            userInfo.setAddress(null == kaiOrderVo.getAddress() ? "" : kaiOrderVo.getAddress());
            Long userId = userService.save(loginInfo, userInfo);
            // 工单客户
            ZjWorkUser workUser = new ZjWorkUser();
            workUser.setId(order.getId());
            workUser.setCustAccId(order.getCustAccId());
            workUser.setHelpOtherCreateOrder(false);
            workUser.setCreateOrderUserId(0L);
            workUser.setUserId(userId);
            workUser.setName(kaiOrderVo.getUsername());
            workUser.setPhone(kaiOrderVo.getUserPhone());
            workUser.setOtherPhone("");
            workUser.setProvince(kaiOrderVo.getProvince());
            workUser.setCity(kaiOrderVo.getCity());
            workUser.setArea(null == kaiOrderVo.getArea()? "" : kaiOrderVo.getArea());
            workUser.setTown("");
            workUser.setAddress(null == kaiOrderVo.getAddress() ? "" : kaiOrderVo.getAddress());
            workUserService.save(workUser);
            // 工单商品
            ZjWorkGoods workGoods = new ZjWorkGoods();
            workGoods.setId(IdWorker.getId());
            workGoods.setCustAccId(order.getCustAccId());
            workGoods.setWorkId(order.getId());
            workGoods.setGoodsId(viewGoods.getId()); // 固定
            workGoods.setGoodsSpecId(viewGoods.getSpecId()); // 固定
            workGoods.setBuyTime(new Date()); //
            workGoods.setEndTime(DateUtils.addDays(workGoods.getBuyTime(), viewGoods.getWarrantyDay()));
            workGoods.setQty(null == kaiOrderVo.getQty()? 1 : kaiOrderVo.getQty());
            workGoodsService.save(workGoods);
            // 工单商品编码
            ZjWorkGoodsCode goodsCode = new ZjWorkGoodsCode();
            goodsCode.setId(IdWorker.getId());
            goodsCode.setCustAccId(order.getCustAccId());
            goodsCode.setWorkId(order.getId());
            goodsCode.setWorkGoodsId(workGoods.getId());
            goodsCode.setCodeId(0L);
            goodsCode.setCode("");
            workGoodsCodeService.save(goodsCode);

            ZjWorkHoubanYunRelation workHoubanYunRelation = new ZjWorkHoubanYunRelation();
            workHoubanYunRelation.setId(order.getId());
            workHoubanYunRelation.setCustAccId(order.getCustAccId());
            workHoubanYunRelation.setTableId(dataObj.getString("table_id"));
            workHoubanYunRelation.setItemId(kaiOrderVo.getItemId());
            workHoubanYunRelationService.save(workHoubanYunRelation);
        }
        // 工单图片
        workImage(workId, kaiOrderVo.getSourceImage());
        // 自定义字段
        if (Objects.equals("安装", kaiOrderVo.getModule())) {
            cInstallField(workId, kaiOrderVo);
        } else {
            cUpdateField(workId, kaiOrderVo);
        }
    }

    /**
     * 取消工单时，修改相关的状态
     * @param workId
     */

    private void updateDispatchNetworkStatus(Long workId) {
        ZjWorkDispatchNetwork dispatchNetwork = workDispatchNetworkService.getByWorkId(workId);
        if (null != dispatchNetwork && dispatchNetwork.getStatus() != WorkConstant.DISPATCH_NETWORK_STATUS_6) {
            ZjWorkDispatchNetwork updateDispatchNetwork = new ZjWorkDispatchNetwork();
            // 存在待审核的结单申请，需要取消
            if (dispatchNetwork.getStatus() == WorkConstant.DISPATCH_NETWORK_STATUS_5) {
                ZjWorkFinishOrder workFinishOrder = workFinishOrderService.getWaitCheckStatementOrder(workId);
                ZjWorkFinishOrder updateWorkFinishOrder = new ZjWorkFinishOrder();
                updateWorkFinishOrder.setId(workFinishOrder.getId());
                updateWorkFinishOrder.setStatus(WorkConstant.WORK_FINISH_ORDER_STATUS_4);
                workFinishOrderService.updateById(updateWorkFinishOrder);
            }
            updateDispatchNetwork.setId(dispatchNetwork.getId());
            updateDispatchNetwork.setStatus(WorkConstant.DISPATCH_NETWORK_STATUS_7);
            workDispatchNetworkService.updateById(updateDispatchNetwork);
        }
        QueryWrapper<ZjWorkDispatchEngineer> engineerQueryWrapper = new QueryWrapper<>();
        engineerQueryWrapper.select("id")
                .eq("work_id", workId)
                .between("status", 1, 3);
        List<ZjWorkDispatchEngineer> engineerList = workDispatchEngineerService.list(engineerQueryWrapper);
        if (CollectionUtil.isNotEmpty(engineerList)) {
            engineerList.forEach(t -> {
                t.setStatus(WorkConstant.DISPATCH_ENGINEER_STATUS_5);
            });
            workDispatchEngineerService.updateBatchById(engineerList);
        }
    }

    // C端安装自定义字段
    private void cInstallField(Long workId, LKaiOrderVo kaiOrderVo) {
        // 工单自定义字段
        List<ZjWorkFieldVal> workFieldValList = new ArrayList<>();
        List<ZjWorkFieldValOption> fieldValOptionList = new ArrayList<>();
        // 门体厚度
        getFieldVal(workId, "门体厚度", 1, HoubanYunOrder.getcInstallWorkModuleFieldId1(), HoubanYunOrder.getcInstallWorkFieldId1(), kaiOrderVo.getCInstallOrderField1(), workFieldValList, fieldValOptionList);
        // 导向片高度
        getFieldVal(workId, "导向片高度", 1, HoubanYunOrder.getcInstallWorkModuleFieldId2(), HoubanYunOrder.getcInstallWorkFieldId2(), kaiOrderVo.getCInstallOrderField2(), workFieldValList, fieldValOptionList);
        // 导向片宽度
        getFieldVal(workId, "导向片宽度", 1, HoubanYunOrder.getcInstallWorkModuleFieldId3(), HoubanYunOrder.getcInstallWorkFieldId3(), kaiOrderVo.getCInstallOrderField3(), workFieldValList, fieldValOptionList);
        // 备注
        getFieldVal(workId, "备注", 1, HoubanYunOrder.getcInstallWorkModuleFieldId4(), HoubanYunOrder.getcInstallWorkFieldId4(), kaiOrderVo.getCInstallOrderField4(), workFieldValList, fieldValOptionList);
        // 产品型号
        getFieldVal(workId, "产品型号", 1, HoubanYunOrder.getcInstallWorkModuleFieldId5(), HoubanYunOrder.getcInstallWorkFieldId5(), kaiOrderVo.getGoodsModel(), workFieldValList, fieldValOptionList);
        // 产品SN/CMEI码
        getFieldVal(workId, "产品SN/CMEI码", 1, HoubanYunOrder.getcInstallWorkModuleFieldId6(), HoubanYunOrder.getcInstallWorkFieldId6(), kaiOrderVo.getSnCode(), workFieldValList, fieldValOptionList);
        // 上传完整产品图片
        getFieldVal(workId, "上传完整产品图片", 5, HoubanYunOrder.getcInstallWorkModuleFieldId7(), HoubanYunOrder.getcInstallWorkFieldId7(), kaiOrderVo.getCInstallOrderField7(), workFieldValList, fieldValOptionList);
        // 门体视频
        getFieldVal(workId, "门体视频", 7, HoubanYunOrder.getcInstallWorkModuleFieldId8(), HoubanYunOrder.getcInstallWorkFieldId8(), kaiOrderVo.getCInstallOrderField8(), workFieldValList, fieldValOptionList);
        // 门体属性
        getFieldVal(workId, "门体属性", 4, HoubanYunOrder.getcInstallWorkModuleFieldId9(), HoubanYunOrder.getcInstallWorkFieldId9(), kaiOrderVo.getCInstallOrderField9(), workFieldValList, fieldValOptionList);
        // 有无天地钩
        getFieldVal(workId, "有无天地钩", 4, HoubanYunOrder.getcInstallWorkModuleFieldId10(), HoubanYunOrder.getcInstallWorkFieldId10(), kaiOrderVo.getCInstallOrderField10(), workFieldValList, fieldValOptionList);
        // 期望上门时间
        getFieldVal(workId, "期望上门时间", 1, HoubanYunOrder.getcInstallWorkModuleFieldId11(), HoubanYunOrder.getcInstallWorkFieldId11(), kaiOrderVo.getCInstallOrderField11(), workFieldValList, fieldValOptionList);
        if (CollectionUtil.isNotEmpty(workFieldValList)) {
            // 删除存在的字段
            workFieldValService.deleteByWorkId(workId);
            workFieldValOptionService.deleteByWorkId(workId);
            // 新增新的字段
            workFieldValService.saveBatch(workFieldValList);
            workFieldValOptionService.saveBatch(fieldValOptionList);
        }
    }

    // C端维修自定义字段
    private void cUpdateField(Long workId, LKaiOrderVo kaiOrderVo) {
        // 工单自定义字段
        List<ZjWorkFieldVal> workFieldValList = new ArrayList<>();
        List<ZjWorkFieldValOption> fieldValOptionList = new ArrayList<>();
        // 服务受理状态
        getFieldVal(workId, "服务受理状态", 1, HoubanYunOrder.getcUpdateWorkModuleFieldId1(), HoubanYunOrder.getcUpdateWorkFieldId1(), kaiOrderVo.getCUpdateOrderField1(), workFieldValList, fieldValOptionList);
        // 故障原因
        getFieldVal(workId, "故障原因", 1, HoubanYunOrder.getcUpdateWorkModuleFieldId2(), HoubanYunOrder.getcUpdateWorkFieldId2(), kaiOrderVo.getCUpdateOrderField2(), workFieldValList, fieldValOptionList);
        // 处理方式
        getFieldVal(workId, "处理方式", 1, HoubanYunOrder.getcUpdateWorkModuleFieldId3(), HoubanYunOrder.getcUpdateWorkFieldId3(), kaiOrderVo.getCUpdateOrderField3(), workFieldValList, fieldValOptionList);
        // 产品型号
        getFieldVal(workId, "产品型号", 1, HoubanYunOrder.getcUpdateWorkModuleFieldId4(), HoubanYunOrder.getcUpdateWorkFieldId4(), kaiOrderVo.getGoodsModel(), workFieldValList, fieldValOptionList);
        // 产品SN/CMEI码
        getFieldVal(workId, "产品SN/CMEI码", 1, HoubanYunOrder.getcUpdateWorkModuleFieldId5(), HoubanYunOrder.getcUpdateWorkFieldId5(), kaiOrderVo.getSnCode(), workFieldValList, fieldValOptionList);
        // 备注
        getFieldVal(workId, "备注", 1, HoubanYunOrder.getcInstallWorkModuleFieldId6(), HoubanYunOrder.getcInstallWorkFieldId6(), kaiOrderVo.getCInstallOrderField4(), workFieldValList, fieldValOptionList);
        if (CollectionUtil.isNotEmpty(workFieldValList)) {
            // 删除存在的字段
            workFieldValService.deleteByWorkId(workId);
            workFieldValOptionService.deleteByWorkId(workId);
            // 新增新的字段
            workFieldValService.saveBatch(workFieldValList);
            workFieldValOptionService.saveBatch(fieldValOptionList);
        }
    }

    /**
     * 是否取消工单，根据伙伴云的定义，无需上门就是取消工单
     * @param kaiOrderVo
     * @return
     */
    private Boolean cancelOrder(LKaiOrderVo kaiOrderVo) {
        return Objects.equals("2", kaiOrderVo.getCancelOrderId());
    }

    private void getFieldVal(Long workId, String name, Integer type, Long moduleFieldId, Long workFieldId, String optVal, List<ZjWorkFieldVal> workFieldValList, List<ZjWorkFieldValOption> fieldValOptionList) {
//        if (StringUtils.isBlank(optVal)) {
//            return;
//        }
        ZjWorkFieldVal val = new ZjWorkFieldVal();
        val.setId(IdWorker.getId());
        val.setCustAccId(HoubanYunOrder.getCustAccId());
        val.setWorkId(workId);
        val.setName(name); //  固定
        val.setType(type); // 固定
        val.setModuleFieldId(moduleFieldId); //
        val.setWorkFieldId(workFieldId); // 固定
        workFieldValList.add(val);

        ZjWorkFieldValOption valOption = new ZjWorkFieldValOption();
        valOption.setId(IdWorker.getId());
        valOption.setCustAccId(HoubanYunOrder.getCustAccId());
        valOption.setWorkId(workId);
        valOption.setWorkFieldValId(val.getId());
        valOption.setOptValue(null != optVal? optVal : "" ); // 取伙伴云返回的值
        fieldValOptionList.add(valOption);
    }
    private void getFieldVal(Long workId, String name, Integer type, Long moduleFieldId, Long workFieldId, List<String> optVal, List<ZjWorkFieldVal> workFieldValList, List<ZjWorkFieldValOption> fieldValOptionList) {
        ZjWorkFieldVal val = new ZjWorkFieldVal();
        val.setId(IdWorker.getId());
        val.setCustAccId(HoubanYunOrder.getCustAccId());
        val.setWorkId(workId);
        val.setName(name); //  固定
        val.setType(type); // 固定
        val.setModuleFieldId(moduleFieldId); //
        val.setWorkFieldId(workFieldId); // 固定
        workFieldValList.add(val);

        for (String v : optVal) {
            ZjWorkFieldValOption valOption = new ZjWorkFieldValOption();
            valOption.setId(IdWorker.getId());
            valOption.setCustAccId(HoubanYunOrder.getCustAccId());
            valOption.setWorkId(workId);
            valOption.setWorkFieldValId(val.getId());
            valOption.setOptValue(null != v? v : ""); // 取伙伴云返回的值
            fieldValOptionList.add(valOption);
        }
    }

    // 工单图片
    private void workImage(Long workId, List<String> images) {
        if (CollectionUtil.isEmpty(images)) {
            return;
        }
        // 删除旧图片
        QueryWrapper<ZjWorkImage> imageQueryWrapper = new QueryWrapper<>();
        imageQueryWrapper.eq("work_id", workId);
        workImageService.remove(imageQueryWrapper);
        List<ZjWorkImage> workImageList = new ArrayList<>();
        ZjWorkImage img = null;
        for (String image : images) {
            img = new ZjWorkImage();
            img.setId(IdWorker.getId());
            img.setCustAccId(HoubanYunOrder.getCustAccId());
            img.setWorkId(workId);
            img.setImage(image);
            workImageList.add(img);
        }
        workImageService.saveBatch(workImageList);
    }
    // 工单费用
    private Integer workFee(Long workId, LKaiOrderVo kaiOrderVo) {
        Integer feeCount = 0;
        Boolean cancelOrder = cancelOrder(kaiOrderVo);
        if (null != kaiOrderVo.getFee1()) {  // 基础费
            feeCount += getWorkFeeDetai(workId, cancelOrder, kaiOrderVo.getOrderNo(), HoubanYunOrder.getFee1Id(), kaiOrderVo.getFee1(), true);
        }
        if (null != kaiOrderVo.getFee2()) { // 加急费\
            feeCount += getWorkFeeDetai(workId, cancelOrder, kaiOrderVo.getOrderNo(), HoubanYunOrder.getFee2Id(), kaiOrderVo.getFee2(), true);
        }
        if (null != kaiOrderVo.getFee3()) { // 开锁费
            feeCount += getWorkFeeDetai(workId, cancelOrder, kaiOrderVo.getOrderNo(), HoubanYunOrder.getFee3Id(), kaiOrderVo.getFee3(), true);
        }
        if (null != kaiOrderVo.getFee4()) { // 远程费
            feeCount += getWorkFeeDetai(workId, cancelOrder, kaiOrderVo.getOrderNo(), HoubanYunOrder.getFee4Id(), kaiOrderVo.getFee4(), true);
        }
        if (null != kaiOrderVo.getFee5()) { // 使用师傅配件费
            feeCount += getWorkFeeDetai(workId, cancelOrder, kaiOrderVo.getOrderNo(), HoubanYunOrder.getFee5Id(), kaiOrderVo.getFee5(), true);
        }
        if (null != kaiOrderVo.getFee6()) { // 批量服务费
            feeCount += getWorkFeeDetai(workId, cancelOrder, kaiOrderVo.getOrderNo(), HoubanYunOrder.getFee10Id(), kaiOrderVo.getFee6(), true);
        }
        if (null != kaiOrderVo.getFee7()) { // 空跑费
            feeCount += getWorkFeeDetai(workId, cancelOrder, kaiOrderVo.getOrderNo(), HoubanYunOrder.getFee6Id(), kaiOrderVo.getFee7(), true);
        }
        if (null != kaiOrderVo.getFee8()) { // 维修总费用
            feeCount += getWorkFeeDetai(workId, cancelOrder, kaiOrderVo.getOrderNo(), HoubanYunOrder.getFee11Id(), kaiOrderVo.getFee8(), true);
        }
        return feeCount;
    }

    /**
     * 工单费用
     * @param workId 工单ID
     * @param cancelOrder 是否取消工单
     * @param workNo 工单单号
     * @param workFeeId 工单费用项目ID
     * @param receiveFactoryPrice 服务费用
     * @param baseFee 是否基础费用：false-不是，true：是，基础费无需审核，直接通过
     * @return
     */
    private Integer getWorkFeeDetai(Long workId, Boolean cancelOrder, String workNo, Long workFeeId, BigDecimal receiveFactoryPrice, boolean baseFee) {
        ZjWorkFeeDetail feeDetail = workFeeDetailService.getByWorkIdAndWorkFeeProjectId(workId, workFeeId);
        if (null != feeDetail) {
            if (!receiveFactoryPrice.toString().endsWith("^\\.[0-9]?$")) {
                receiveFactoryPrice = new BigDecimal("0.00").add(receiveFactoryPrice);
            }
            if (Objects.equals(feeDetail.getReceiveFactoryPrice(), receiveFactoryPrice)) {
                return 0;
            }
            // 工单已取消
            if (cancelOrder) {
                ZjWorkFee workFee = workFeeService.getById(feeDetail.getWorkFeeId());
                if (workFee.getStatus() == WorkConstant.WORK_FEE_STATUS_1) {
                    ZjWorkFee updateWorkFee = new ZjWorkFee();
                    updateWorkFee.setId(workFee.getId());
                    updateWorkFee.setStatus(WorkConstant.WORK_FEE_STATUS_5);
                    workFeeService.updateById(updateWorkFee);
                }
                if (feeDetail.getStatus() == 1) {
                    feeDetail.setStatus(3);
                    workFeeDetailService.updateById(feeDetail);
                }
                String message = "工单已取消，服务费用一并取消";
                WorkServiceLog.saveServiceFeeLog(new WorkFeeLogVo(HoubanYunOrder.getCustAccId(), workId, feeDetail.getWorkFeeId(), 0L, "乐开伙伴云", "取消服务费", message));
                WorkServiceLog.saveLKaiHoubanyunOrder(new WorkLogVo(HoubanYunOrder.getCustAccId(), "乐开伙伴云", workId, "取消服务费",  message));
                return 0;
            }
            String message = "修改服务费，从 " + feeDetail.getReceiveFactoryPrice() + " 更改为 " + receiveFactoryPrice;
            feeDetail.setReceiveFactoryPrice(receiveFactoryPrice);
            workFeeDetailService.updateById(feeDetail);
            WorkServiceLog.saveServiceFeeLog(new WorkFeeLogVo(HoubanYunOrder.getCustAccId(), workId, feeDetail.getWorkFeeId(), 0L, "乐开伙伴云", "修改服务费", message));
            WorkServiceLog.saveLKaiHoubanyunOrder(new WorkLogVo(HoubanYunOrder.getCustAccId(), "乐开伙伴云", workId, "乐开伙伴云更改服务费",  message));
            return 0;
        }
        // 判断费用如果为0，则不新增
        if (Objects.equals("0", receiveFactoryPrice.toString())) {
            return 0;
        }
        ZjWorkFee workFee = new ZjWorkFee();
        workFee.setId(IdWorker.getId());
        workFee.setCustAccId(HoubanYunOrder.getCustAccId());
        workFee.setWorkId(workId);
        workFee.setWorkNo(workNo);
        workFee.setCode(ZbOrderNoUtil.orderFeeNo(HoubanYunOrder.getCustAccId()));
        // 工单取消，状态变为 已取消
        workFee.setStatus(cancelOrder? WorkConstant.WORK_FEE_STATUS_5 : baseFee? WorkConstant.WORK_FEE_STATUS_2 : WorkConstant.WORK_FEE_STATUS_1);
        workFee.setNetworkId(0L);
        workFee.setNetworkManagerEmpId(0L);
        workFee.setNetworkEngineerEmpId(0L);
        workFee.setApplyRemark("");
        workFee.setApplyEmpType(3);
        workFee.setApplyEmpId(0L);
        workFee.setApplyEmp("");
        workFee.setReceive(false);
        workFee.setReviewEmpId(0L);
        workFee.setReviewEmp("");
        workFee.setReviewRemark("");
        workFeeService.save(workFee);

        feeDetail = new ZjWorkFeeDetail();
        feeDetail.setCustAccId(HoubanYunOrder.getCustAccId());
        feeDetail.setWorkFeeId(workFee.getId());
        feeDetail.setWorkId(workId);
        // 工单取消，状态变为已取消
        feeDetail.setStatus(cancelOrder? 3 : baseFee? 2 : 1);
        feeDetail.setType(1);
        feeDetail.setWorkFeeProjectId(workFeeId);
        feeDetail.setSurePriceStatus(0);
        feeDetail.setNetworkApply(false);
        feeDetail.setPrice(new BigDecimal("0.00"));
        feeDetail.setPayNetworkPrice(new BigDecimal("0.00"));
        feeDetail.setReceiveFactoryPrice(receiveFactoryPrice);
        feeDetail.setQty(1);
        feeDetail.setRemark("");
        workFeeDetailService.save(feeDetail);
        WorkServiceLog.saveServiceFeeLog(new WorkFeeLogVo(HoubanYunOrder.getCustAccId(), workId, workFee.getId(), 0L, "乐开伙伴云", "新增服务费", ""));
        WorkServiceLog.saveLKaiHoubanyunOrder(new WorkLogVo(HoubanYunOrder.getCustAccId(), "乐开伙伴云", workId, "乐开伙伴云新增服务费"));
        return 0;
    }

    // 根据key获取内容
    private String getTitle(JSONObject obj, String keyId) {
        if (null == obj) {
            return "";
        }
        if (JSON.isValidArray(obj.getString(keyId))) {
            List<JSONObject> keyObjs = JSON.parseArray(obj.getString(keyId), JSONObject.class);
            if (CollectionUtil.isEmpty(keyObjs)) {
                return "";
            }
            String title = keyObjs.get(0).getString("title");
            if (StringUtils.isNotBlank(title)) {
                return title;
            }
            String name = keyObjs.get(0).getString("name");
            return name;
        }
        if (JSON.isValidObject(obj.getString(keyId))) {
            JSONObject keyObj = JSON.parseObject(obj.getString(keyId), JSONObject.class);
            if (null == keyObj) {
                return "";
            }
            return keyObj.getString("title");
        }
        return obj.getString(keyId);
    }

    // 根据key获取内容
    private String getIdVal(JSONObject obj, String keyId) {
        if (null == obj) {
            return "";
        }
        if (JSON.isValidArray(obj.getString(keyId))) {
            List<JSONObject> keyObjs = JSON.parseArray(obj.getString(keyId), JSONObject.class);
            if (CollectionUtil.isEmpty(keyObjs)) {
                return "";
            }
            String title = keyObjs.get(0).getString("id");
            if (StringUtils.isNotBlank(title)) {
                return title;
            }
            String name = keyObjs.get(0).getString("id");
            return name;
        }
        if (JSON.isValidObject(obj.getString(keyId))) {
            JSONObject keyObj = JSON.parseObject(obj.getString(keyId), JSONObject.class);
            if (null == keyObj) {
                return "";
            }
            return keyObj.getString("id");
        }
        return obj.getString(keyId);
    }

    // 工单等级
    private Long getOrderLevel(String level) {
        QueryWrapper<ZjWorkLevel> levelQueryWrapper = new QueryWrapper<>();
        levelQueryWrapper.select("id", "name")
                .eq("cust_acc_id", HoubanYunOrder.getCustAccId())
                .eq("name", level);
        List<ZjWorkLevel> list = workLevelService.list(levelQueryWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            return list.get(0).getId();
        }
        ZjWorkLevel workLevel = new ZjWorkLevel();
        workLevel.setId(IdWorker.getId());
        workLevel.setCustAccId(HoubanYunOrder.getCustAccId());
        workLevel.setName(level);
        workLevel.setColor("");
        workLevel.setWeight(1);
        workLevel.setDefaultLevel(false);
        workLevel.setDisalbed(false);
        workLevelService.save(workLevel);
        return workLevel.getId();
    }


    // 保存B端维修工单
    @Override
    @Transactional
    public void saveBOrder(String data) {
        JSONObject obj = JSON.parseObject(data, JSONObject.class);
        if (null == obj) {
            return;
        }
        JSONObject headerObj = JSON.parseObject(obj.getString("header"), JSONObject.class);
        // 过滤掉事件类型不是 item.update 的数据
        if (!Objects.equals(EVENT_TYPE, headerObj.getString("event_type"))) {
            return;
        }
        JSONObject dataObj = JSON.parseObject(obj.getString("data"), JSONObject.class);
        if (null == dataObj) {
            return;
        }
        JSONObject itemObj = JSON.parseObject(dataObj.getString("item"), JSONObject.class);
        if (null == itemObj) {
            return;
        }
        // 过滤掉非叮咚的工单数据
        JSONObject fieldsObj = JSON.parseObject(itemObj.getString("fields"), JSONObject.class);
        // 负责服务商，过滤非叮咚的工单
        List<JSONObject> ddNetworkObjs = JSON.parseArray(fieldsObj.getString("2200000466059900"), JSONObject.class);
        if (CollectionUtil.isEmpty(ddNetworkObjs)) {
            log.info("伙伴云推送的数据(没有服务商字段或服务商字段为空，不做处理)，时间：{}， 数据：{}", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"), data);
            return;
        }
        JSONObject ddNetworkObj = ddNetworkObjs.get(0);
        if (!workHoubanYunNetworkService.existByHoubanYunNetworkItemId(HoubanYunOrder.getCustAccId(), ddNetworkObj.getString("item_id"))) {
            log.info("伙伴云推送的数据(当前工单不是叮咚的工单，不做处理)，时间：{}，item_id：{}， 数据：{}", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"), ddNetworkObj.getString("item_id"), data);
            return;
        }
        Date createdOn = itemObj.getDate("created_on");
        Date appointDate = ZbDateUtil.getAppointDate("2024-08-30", ZbDateUtil.DATE_FORMAT);
        if (null == appointDate) {
            log.info("C端伙伴云推送的叮咚历史数据，创建时间为空，时间：{}", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            return;
        }
        if (createdOn.before(appointDate)) {
            log.info("C端伙伴云推送的叮咚历史数据，时间：{}", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            return;
        }
        System.out.println("=============================================   B端工单分割线 start   ===============================================================");
        log.info("B端伙伴云推送的叮咚数据，时间：{}", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        log.info("B端伙伴云推送的叮咚数据：{}", data);
        log.info("B端伙伴云推送的叮咚数据，时间：{}", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        System.out.println("=============================================   B端工单分割线   end   ===============================================================");
        LKaiBOrderVo bKaiOrderVo = new LKaiBOrderVo();
        bKaiOrderVo.setItemId(itemObj.getString("item_id"));
        JSONObject createdBy = JSON.parseObject(itemObj.getString("created_by"), JSONObject.class);
        bKaiOrderVo.setCreatedByName(null != createdBy? createdBy.getString("name") : "");
        bKaiOrderVo.setCreatedTime(createdOn);

        JSONObject updatedBy = JSON.parseObject(itemObj.getString("updated_by"), JSONObject.class);
        bKaiOrderVo.setUpdateByName(null != updatedBy? updatedBy.getString("name") : "");
        bKaiOrderVo.setUpdateTime(itemObj.getDate("updated_on"));
        bKaiOrderVo.setTitle(itemObj.getString("title"));
        bKaiOrderVo.setOrderNo(getTitle(fieldsObj, "2200000464559694")); //fieldsObj.getString("2200000464559694"));
        bKaiOrderVo.setModule(getTitle(fieldsObj,  "2200000465310979"));
        bKaiOrderVo.setLevel(getTitle(fieldsObj, "2200000464559699"));
        bKaiOrderVo.setSource(getTitle(fieldsObj,  "2200000464559695"));
        bKaiOrderVo.setUserType(getTitle(fieldsObj,  "2200000465310980"));
        bKaiOrderVo.setUsername(fieldsObj.getString("2200000464559697"));
        bKaiOrderVo.setUserPhone(fieldsObj.getString("2200000464559698"));
        bKaiOrderVo.setProvince(getTitle(fieldsObj,  "2200000471274813"));
        bKaiOrderVo.setCity(getTitle(fieldsObj,  "2200000471274814"));
        bKaiOrderVo.setArea(getTitle(fieldsObj,  "2200000473274193"));
        bKaiOrderVo.setAddress(fieldsObj.getString("2200000465870871"));
        bKaiOrderVo.setGoodsType(getTitle(fieldsObj,  "2200000465226751"));
        bKaiOrderVo.setGoodsModel(fieldsObj.getString("2200000464711078"));
        bKaiOrderVo.setContent(fieldsObj.getString("2200000464559704"));
        bKaiOrderVo.setQty(fieldsObj.getInteger("2200000466700182"));
        bKaiOrderVo.setHandlerTime(fieldsObj.getDate("2200000464559707"));
        bKaiOrderVo.setTotalFee(fieldsObj.getBigDecimal("2200000469555716"));
        bKaiOrderVo.setHouseNumber(fieldsObj.getString("2200000473274194"));
        bKaiOrderVo.setFaultRemark(getTitle(fieldsObj, "2200000468353764"));
        bKaiOrderVo.setCancelOrderId(getIdVal(fieldsObj, "2200000464693632"));
        bKaiOrderVo.setCUpdateOrderField1(getTitle(fieldsObj, "2200000464693632"));
        bKaiOrderVo.setCUpdateOrderField2(getTitle(fieldsObj, "2200000464693628"));
        bKaiOrderVo.setCUpdateOrderField3(getTitle(fieldsObj, "2200000468353764"));
//        bKaiOrderVo.setFee1(fieldsObj.getBigDecimal("2200000465898487")); // 基础费
//        bKaiOrderVo.setFee2(fieldsObj.getBigDecimal("2200000465898488")); // 加急费
//        bKaiOrderVo.setFee3(fieldsObj.getBigDecimal("2200000465902372")); // 开锁费
//        bKaiOrderVo.setFee4(fieldsObj.getBigDecimal("2200000465902373")); // 远程费
//        bKaiOrderVo.setFee6(fieldsObj.getBigDecimal("2200000466362476")); // 批量服务费
        bKaiOrderVo.setFee8(fieldsObj.getBigDecimal("2200000466700183")); // 维修总费用
        List<String> fileIds = new ArrayList<>();
        getImageId(fieldsObj, "2200000470585685", fileIds); // 封面
        getImageId(fieldsObj, "2200000464559703", fileIds); // 故障图片
//        getImageId(fieldsObj, "2200000471536074", fileIds); // 门体正面照片
        bKaiOrderVo.setSourceImage(getBatchFiles(fileIds));

        ZjWorkHoubanYunRelation houbanYunRelation = workHoubanYunRelationService.getByItemId(bKaiOrderVo.getItemId());
        Long workId = null;
        // 是否有取消工单的
        Boolean cancelOrder = cancelOrder(bKaiOrderVo);
        // 修改
        if (null != houbanYunRelation) {
            ZjWorkOrder order = new ZjWorkOrder();
            order.setId(houbanYunRelation.getId());
            order.setCode(bKaiOrderVo.getOrderNo());
//            if (null != bKaiOrderVo.getFee1()) {
//                order.setModulePrice(bKaiOrderVo.getFee1());
//            }
            // 取消工单
            if (cancelOrder) {
                order.setStatus(WorkConstant.WORK_STATUS_5);
            }
            order.setWorkLevelId(getOrderLevel(bKaiOrderVo.getLevel()));
            order.setUpdateEmp(bKaiOrderVo.getUpdateByName());
            order.setGmtUpdate(bKaiOrderVo.getUpdateTime());
            workOrderService.updateById(order);
            workId = order.getId();

            // 工单客户
            ZjWorkUser workUser = new ZjWorkUser();
            workUser.setId(order.getId());
            workUser.setName(bKaiOrderVo.getUsername());
            workUser.setPhone(bKaiOrderVo.getUserPhone());
            workUser.setOtherPhone("");
            workUser.setProvince(bKaiOrderVo.getProvince());
            workUser.setCity(bKaiOrderVo.getCity());
            workUser.setArea(null == bKaiOrderVo.getArea()? "" : bKaiOrderVo.getArea());
            workUser.setTown("");
            if (null != bKaiOrderVo.getAddress()) {
                workUser.setAddress(bKaiOrderVo.getAddress());
            }
            workUserService.updateById(workUser);
            WorkServiceLog.saveLKaiHoubanyunOrder(new WorkLogVo(HoubanYunOrder.getCustAccId(), "乐开伙伴云", order.getId(), cancelOrder? "乐开伙伴云取消工单" : "乐开伙伴云更新工单"));
            // 工单费用
//            ZjWorkDetail workDetail = workDetailService.getById(workId);
            Integer workFeeCount = workFee(workId, bKaiOrderVo);
            ZjWorkDetail detail = new ZjWorkDetail();
            detail.setId(order.getId());
            detail.setNoReviewApplyWorkFeeNum(0);
            detail.setContent(null == bKaiOrderVo.getContent() ? "" : bKaiOrderVo.getContent());
            if (cancelOrder) {
                updateDispatchNetworkStatus(order.getId());
                detail.setNoReviewApplyWorkFeeNum(0);
                detail.setEndOrderApply(false);
            }
            workDetailService.updateById(detail);
        } else {
            // 查询工单模块
            if (Objects.equals("安装", bKaiOrderVo.getModule())) {
                return;
            }
            ZjWorkModule module = null;
            ViewGoods viewGoods = null;
            // 维修
            module = workModuleService.getById(HoubanYunOrder.getbUpdateModuleId());
            viewGoods = viewGoodsService.getByGoodsTypeAndGoodsIdAndGoodsSpecId(1, HoubanYunOrder.getbUpdateGoodsId(), HoubanYunOrder.getbUpdateGoodsSpecId());
            ZjFactory factory = factoryService.getById(HoubanYunOrder.getFactoryId());
            // 工单数据
            ZjWorkOrder order = new ZjWorkOrder();
            order.setId(IdWorker.getId());
            order.setCustAccId(HoubanYunOrder.getCustAccId()); // 固定
            order.setFactoryId(HoubanYunOrder.getFactoryId()); // 固定
            order.setCode(bKaiOrderVo.getOrderNo());
            order.setStatus(cancelOrder? WorkConstant.WORK_STATUS_5 : WorkConstant.WORK_STATUS_1);
            order.setArchived(false);
            order.setModuleId(module.getId()); // 固定
            order.setAssignEmp(false);
            order.setEmpId(0L);
            order.setAssignEmpTime(null);
            order.setNetworkId(0L);
            order.setNetworkEmpId(0L);
            order.setEndTime(null);
            order.setNewAdvance(0);
            order.setWaitCopeEvent(0);
            order.setOverinsured(module.getOverinsured()); // 根据模块取
            order.setReminderNum(0);
            order.setWarrantyDay(module.getWarrantyDay()); // 根据模块取
            order.setSource(WorkConstant.WORK_SOURCE_9); // 来源
            order.setWorkLevelId(getOrderLevel(bKaiOrderVo.getLevel()));
            order.setAllInclusiveFee(false);
            order.setModulePrice(new BigDecimal("0.00"));
            order.setNetworkModulePrice(new BigDecimal("0.00"));
            order.setCollectCustomerPrice(new BigDecimal("0.00"));
            order.setFactorySettlementDeductionPrice(new BigDecimal("0.00"));
            order.setNetworkSettlementDeductionPrice(new BigDecimal("0.00"));
            order.setEndOrder(false);
            order.setSettlementStatus(WorkConstant.WORK_SETTLEMENT_STATUS_0);
            order.setWithdrawFreezeDay(0);
            order.setComment(false);
            order.setChangeOrder(false);
            order.setSuspendStatus(0);
            order.setCreateEmpId(0L);
            order.setCreateEmp(bKaiOrderVo.getCreatedByName());
            order.setUpdateEmpId(0L);
            order.setUpdateEmp(bKaiOrderVo.getUpdateByName());
            order.setFactoryRemark("");
            order.setCreateFactory(null == factory ? "" : factory.getName());
            order.setCreateEmpType(4);
            order.setGmtCreate(bKaiOrderVo.getCreatedTime());
            order.setGmtUpdate(bKaiOrderVo.getUpdateTime());
            workOrderService.save(order);
            log.info("乐开B端推送工单：{}", order);
            WorkServiceLog.saveLKaiHoubanyunOrder(new WorkLogVo(order.getCustAccId(), "乐开伙伴云", order.getId(), "乐开伙伴云创建工单"));

            workId = order.getId();
            // 工单费用
            Integer workFeeCount = workFee(workId, bKaiOrderVo);
            // 工单详细数据
            ZjWorkDetail detail = new ZjWorkDetail();
            detail.setId(order.getId());
            detail.setCustAccId(order.getCustAccId());
            detail.setOneTypeId(0L);
            detail.setTwoTypeId(0L);
            detail.setThreeTypeId(0L);
            detail.setOneWayId(0L);
            detail.setTwoWayId(0L);
            detail.setThreeWayId(0L);
            detail.setContent(null == bKaiOrderVo.getContent() ? "" : bKaiOrderVo.getContent());
            detail.setNoReviewApplyWorkFeeNum(0);
            detail.setNoReviewApplyWorkSpareNum(0);
            detail.setEndOrderApply(false);
            detail.setCancelOrderApply(false);
            detail.setChangeNetworkApply(false);
            detail.setDispatchEmpId(0L);
            detail.setDispatchTime(null);
            detail.setReservation(false);
            detail.setStatementVerifCode(RandomUtil.randomNumber6());
            detail.setCollectCustomerPriceVoucher("");
            workDetailService.save(detail);

            AccounLoginInfo loginInfo = new AccounLoginInfo(0L, "", "", "", false, "");
            loginInfo.setCustAccId(order.getCustAccId());
            UserInfo userInfo = new UserInfo();
            userInfo.setName(bKaiOrderVo.getUsername());
            userInfo.setPhone(bKaiOrderVo.getUserPhone());
            userInfo.setProvince(bKaiOrderVo.getProvince());
            userInfo.setCity(bKaiOrderVo.getCity());
            userInfo.setArea(null == bKaiOrderVo.getArea()? "" : bKaiOrderVo.getArea());
            userInfo.setTown("");
            userInfo.setAddress(null == bKaiOrderVo.getUserAddr() ? "" : bKaiOrderVo.getUserAddr());
            Long userId = userService.save(loginInfo, userInfo);
            // 工单客户
            ZjWorkUser workUser = new ZjWorkUser();
            workUser.setId(order.getId());
            workUser.setCustAccId(order.getCustAccId());
            workUser.setHelpOtherCreateOrder(false);
            workUser.setCreateOrderUserId(0L);
            workUser.setUserId(userId);
            workUser.setName(bKaiOrderVo.getUsername());
            workUser.setPhone(bKaiOrderVo.getUserPhone());
            workUser.setOtherPhone("");
            workUser.setProvince(bKaiOrderVo.getProvince());
            workUser.setCity(bKaiOrderVo.getCity());
            workUser.setArea(null == bKaiOrderVo.getArea()? "" : bKaiOrderVo.getArea());
            workUser.setTown("");
            workUser.setAddress(null == bKaiOrderVo.getAddress() ? "" : bKaiOrderVo.getAddress());
            workUserService.save(workUser);
            // 工单商品
            ZjWorkGoods workGoods = new ZjWorkGoods();
            workGoods.setId(IdWorker.getId());
            workGoods.setCustAccId(order.getCustAccId());
            workGoods.setWorkId(order.getId());
            workGoods.setGoodsId(viewGoods.getId()); // 固定
            workGoods.setGoodsSpecId(viewGoods.getSpecId()); // 固定
            workGoods.setBuyTime(new Date()); //
            workGoods.setEndTime(DateUtils.addDays(workGoods.getBuyTime(), viewGoods.getWarrantyDay()));
            workGoods.setQty(null == bKaiOrderVo.getQty()? 1 : bKaiOrderVo.getQty());
            workGoodsService.save(workGoods);
            // 工单商品编码
            ZjWorkGoodsCode goodsCode = new ZjWorkGoodsCode();
            goodsCode.setId(IdWorker.getId());
            goodsCode.setCustAccId(order.getCustAccId());
            goodsCode.setWorkId(order.getId());
            goodsCode.setWorkGoodsId(workGoods.getId());
            goodsCode.setCodeId(0L);
            goodsCode.setCode("");
            workGoodsCodeService.save(goodsCode);

            ZjWorkHoubanYunRelation workHoubanYunRelation = new ZjWorkHoubanYunRelation();
            workHoubanYunRelation.setId(order.getId());
            workHoubanYunRelation.setCustAccId(order.getCustAccId());
            workHoubanYunRelation.setTableId(dataObj.getString("table_id"));
            workHoubanYunRelation.setItemId(bKaiOrderVo.getItemId());
            workHoubanYunRelationService.save(workHoubanYunRelation);
        }
        // 工单图片
        workImage(workId, bKaiOrderVo.getSourceImage());
        // 自定义字段
        bUpdateField(workId, bKaiOrderVo);
    }

    // B端维修自定义字段
    private void bUpdateField(Long workId, LKaiBOrderVo bKaiOrderVo) {
        // 工单自定义字段
        List<ZjWorkFieldVal> workFieldValList = new ArrayList<>();
        List<ZjWorkFieldValOption> workFieldValOptionList = new ArrayList<>();
        // 服务受理状态
        getFieldVal(workId, "服务受理状态", 1, HoubanYunOrder.getbUpdateWorkModuleField1(), HoubanYunOrder.getbUpdateWorkFieldId1(), bKaiOrderVo.getCUpdateOrderField1(), workFieldValList, workFieldValOptionList);
        // 故障原因
        getFieldVal(workId, "故障原因", 1, HoubanYunOrder.getbUpdateWorkModuleField2(), HoubanYunOrder.getbUpdateWorkFieldId2(), bKaiOrderVo.getCUpdateOrderField2(), workFieldValList, workFieldValOptionList);
        // 处理方式
        getFieldVal(workId, "处理方式", 1, HoubanYunOrder.getbUpdateWorkModuleField3(), HoubanYunOrder.getbUpdateWorkFieldId3(), bKaiOrderVo.getCUpdateOrderField3(), workFieldValList, workFieldValOptionList);
        // 门牌号
        getFieldVal(workId, "门牌号", 1, HoubanYunOrder.getbUpdateWorkModuleField4(), HoubanYunOrder.getbUpdateWorkFieldId4(), bKaiOrderVo.getHouseNumber(), workFieldValList, workFieldValOptionList);
        // 故障说明备注
        getFieldVal(workId, "故障说明备注", 1, HoubanYunOrder.getbUpdateWorkModuleField5(), HoubanYunOrder.getbUpdateWorkFieldId5(), bKaiOrderVo.getFaultRemark(), workFieldValList, workFieldValOptionList);
        // 产品型号
        getFieldVal(workId, "产品型号", 1, HoubanYunOrder.getbUpdateWorkModuleField6(), HoubanYunOrder.getbUpdateWorkFieldId6(), bKaiOrderVo.getGoodsModel(), workFieldValList, workFieldValOptionList);
        if (CollectionUtil.isNotEmpty(workFieldValList)) {
            // 删除存在的字段
            workFieldValService.deleteByWorkId(workId);
            workFieldValOptionService.deleteByWorkId(workId);
            // 新增新的字段
            workFieldValService.saveBatch(workFieldValList);
            workFieldValOptionService.saveBatch(workFieldValOptionList);
        }
    }


    private void getImageId(JSONObject fieldsObj, String fieldId, List<String> fileIds) {
        List<JSONObject> images = JSON.parseArray(fieldsObj.getString(fieldId), JSONObject.class);
        if (null == images) {
            return;
        }
        for (JSONObject image : images) {
            fileIds.add(image.getString("file_id"));
        }
    }

    /**
     * 批量获取文件
     * @param fileIds
     */
    private List<String> getBatchFiles(List<String> fileIds) {
        if (CollectionUtil.isEmpty(fileIds)) {
            return new ArrayList<>();
        }
        String url = "https://api.huoban.com/openapi/v1/files";
        // 封装请求头
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Open-Authorization", HoubanYunSecret.getApiKey()); // appKey
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("file_ids", fileIds);
        String post = HttpClientUtil.post(url, headerMap, paramMap);
        JSONObject postObj = JSON.parseObject(post, JSONObject.class);
        if (postObj.getInteger("code") != 0) {
            return new ArrayList<>();
        }
        JSONObject dataObj = JSON.parseObject(postObj.getString("data"), JSONObject.class);
        List<JSONObject> successObjs = JSON.parseArray(dataObj.getString("success"), JSONObject.class);
        List<String> imageList = new ArrayList<>();
        JSONObject linkObj = null;
        String fileName = null;
        ZjCustomer customer = customerService.getById(HoubanYunOrder.getCustAccId());
        String savePath = FilePath.annexUploadPath() + customer.getAnnexCode() + "/order/" + DateFormatUtils.format(new Date(), "yyyy-MM");
        String visiPath = FilePath.annexVisitPath() + customer.getAnnexCode() + "/order/" + DateFormatUtils.format(new Date(), "yyyy-MM");
        String filePath = null;
        for (JSONObject successObj : successObjs) {
            linkObj = JSON.parseObject(successObj.getString("link"), JSONObject.class);
            if (null == linkObj) {
                continue;
            }
            fileName = successObj.getString("name");
            if (StringUtils.isBlank(fileName)) {
                fileName = UUID.randomUUID().toString().replaceAll("-", "") + ".png";
            }
            filePath = DownLoadNetworkFileUtil.downLoadNetworkImage(linkObj.getString("source"), savePath, visiPath, fileName);
            if (StringUtils.isBlank(filePath)) {
                continue;
            }
            imageList.add(DomainPath.domain() + filePath);
        }
        return imageList;
    }


}
